<?php
/**
 * A build script for the db
 *
 *
 **/
require 'db.php';

try {
  $db = new PDO($db_name, $db_user, $db_pass, $db_options);
  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);

} catch ( PDOException $e ) {
  die( $e->getMessage() );
} catch ( Exception $e ) {
  die( $e->getMessage() );
}

try {
  $db->beginTransaction();
  $db->exec( 'DROP TABLE IF EXISTS post;' );
  $db->exec( 'DROP TABLE IF EXISTS thread;' );
  $db->exec( 'DROP TABLE IF EXISTS forum;' );
  $db->exec( 'DROP TABLE IF EXISTS perms;' ); 
  $db->exec( 'DROP TABLE IF EXISTS user;' );

  $db->exec( 'CREATE TABLE post (id INTEGER PRIMARY KEY, name Text(200) NOT NULL, datum CLOB NOT NULL, rank Integer NOT NULL, date Text(10), time Text(8), tid Integer NOT NULL, uid Integer);' );
  $db->exec( 'CREATE TABLE thread (id INTEGER PRIMARY KEY, fid Integer NOT NULL, rank Integer NOT NULL, mode Text(200));' );
  $db->exec( 'CREATE TABLE forum (id INTEGER PRIMARY KEY, name Text(200) NOT NULL, datum Text(200) NOT NULL, rank Integer NOT NULL);' );
  $db->exec( 'CREATE TABLE perms (perm Text(250) NOT NULL, uid Integer NOT NULL);' );
  $db->exec( 'CREATE TABLE user (uid INTEGER PRIMARY KEY, name Text(200) UNIQUE NOT NULL, pass Text(250) NOT NULL, mail Text(200) UNIQUE NOT NULL);');

  $db->exec( 'INSERT INTO user (uid, name, pass, mail) VALUES (0, "guest", "", "");' );
  
  $db->exec( 'INSERT INTO forum (name, datum, rank) VALUES("f1","lots of love",1)');
  $db->exec( 'INSERT INTO thread (fid, rank, mode) VALUES((SELECT MAX(id) FROM forum),1,"none")' );
  $db->exec( 'INSERT INTO post (name, datum, rank, date, tid, uid) 
                   VALUES( "a1t", "a1b", 1, 1182617486, (SELECT MAX(id) FROM thread), 0 )' );
  $db->exec( 'INSERT INTO post (name, datum, rank, date, tid, uid) 
                   VALUES( "a2t", "a2b", 2, 1182617487, (SELECT MAX(id) FROM thread), 0 )' );
  $db->exec( 'INSERT INTO thread (fid, rank, mode) VALUES(1,2,"none")' );
  $db->exec( 'INSERT INTO post (name, datum, rank, date, tid, uid) 
                   VALUES( "b1t", "b1b", 1, 1182617486, (SELECT MAX(id) FROM thread), 0 )' );
  $db->exec( 'INSERT INTO post (name, datum, rank, date, tid, uid) 
                   VALUES( "b2t", "b2b", 2, 1182617486, (SELECT MAX(id) FROM thread), 0 )' );

  $db->exec( 'INSERT INTO forum (name, datum, rank) VALUES("f2","lots of love",1)');
  $db->exec( 'INSERT INTO thread (fid, rank, mode) VALUES((SELECT MAX(id) FROM forum),1,"none")' );
  $db->exec( 'INSERT INTO post (name, datum, rank, date, tid, uid) 
                   VALUES( "A1t", "A1b", 1, 1182617486, (SELECT MAX(id) FROM thread), 0 )' );

  $db->commit();
} catch ( Exception $e ) {
  $db->rollBack();
  die( $e->getMessage() );
}

echo 'DB BUILT';

?>
